package com.totoro.tyrank.mapper.impl;

import com.totoro.tyrank.TyRank;
import com.totoro.tyrank.constants.StaticSystemVarConst;
import com.totoro.tyrank.data.RankData;
import com.totoro.tyrank.mapper.RankDataMapper;
import com.totoro.tyrank.utils.ListUtil;
import org.bukkit.Bukkit;

import java.util.List;

public class RankDataMapperImpl implements RankDataMapper {
    @Override
    public List<RankData> selectAllRankData() {
        String sql = "select * from ty_rank_data";
        try {
            return TyRank.getBaseDao().baseQuery(sql, RankData.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public RankData selectRankDataByRankId(String rankId) {
        String sql = "select * from ty_rank_data where rank_id = ? limit 1";
        try{
            return TyRank.getBaseDao().baseQuery(sql, RankData.class, rankId).stream().findFirst().orElse(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean selectIsHaveRankByRankId(String rankId) {
        String sql = "select 1 from ty_rank_data where rank_id = ? limit 1";
        try {
            List<Long> singleQuery = TyRank.getBaseDao().singleQuery(sql, Long.class, rankId);
            return ListUtil.isNotBlank(singleQuery);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void insertRankData(RankData rankData) {
        String sql = "insert into ty_rank_data (rank_id, is_end, update_date_time) values (?,?,?)";
        try {
            TyRank.getBaseDao().executeUpdate(sql, rankData.getRankId(), rankData.getIsEnd().toString(), rankData.getUpdateDateTime().format(StaticSystemVarConst.DATE_FORMATTER));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateRankData(RankData rankData) {
        String sql = "update ty_rank_data set is_end = ?, update_date_time = ? where rank_id = ?";
        try {
            TyRank.getBaseDao().executeUpdate(sql, rankData.getIsEnd().toString(), rankData.getUpdateDateTime().format(StaticSystemVarConst.DATE_FORMATTER), rankData.getRankId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void removeRankData(String rankId) {
        String sql = "delete from ty_rank_data where rank_id = ?";
        try {
            TyRank.getBaseDao().executeUpdate(sql, rankId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
